package material

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/framework/dao"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

// ProcessMaterialTemplateListAndTotal 获取素材模板列表和总数
func (m *sMaterial) ProcessMaterialTemplateListAndTotal(ctx context.Context, in model.CommonListAndTotalInput, list interface{}, total *int) error {
	if in.Where == nil || g.IsNil(in.Where) {
		return gerror.New(`缺少请求参数`)
	}
	return dao.MaterialTemplate.Ctx(ctx).
		OmitNilWhere().
		Where(in.Where).
		Page(in.Page, in.Size).
		Order(in.Sort).
		ScanAndCount(list, total, true)
}

// ProcessMaterialTemplateDetail 获取素材模板详情
func (m *sMaterial) ProcessMaterialTemplateDetail(ctx context.Context, where interface{}, detail interface{}) error {
	if where == nil || g.IsNil(where) {
		return gerror.New(`缺少请求参数`)
	}
	return dao.MaterialTemplate.Ctx(ctx).
		Where(where).
		Scan(detail)
}

// CheckMaterialTemplateExists 检测素材模板是否存在
func (m *sMaterial) CheckMaterialTemplateExists(ctx context.Context, where interface{}) (bool, error) {
	if where == nil || g.IsNil(where) {
		return false, gerror.New(`缺少请求参数`)
	}
	total, err := dao.MaterialTemplate.Ctx(ctx).
		OmitNilWhere().
		Where(where).
		Count()
	if err != nil {
		return false, err
	}
	return total > 0, nil
}

// ProcessMaterialTemplateDetailById 通过素材ID获取素材模板详情
func (m *sMaterial) ProcessMaterialTemplateDetailById(ctx context.Context, tid uint, detail interface{}) error {
	return m.ProcessMaterialTemplateDetail(
		ctx, g.Map{dao.MaterialTemplate.Columns().Id: tid}, detail,
	)
}

// CheckMaterialTemplateExistsById 通过模板ID检测素材模板是否存在
func (m *sMaterial) CheckMaterialTemplateExistsById(ctx context.Context, tid uint) bool {
	res, err := m.CheckMaterialTemplateExists(ctx, g.Map{dao.MaterialTemplate.Columns().Id: tid})
	if err != nil {
		return false
	}
	return res
}

// ProcessMaterialTemplateScan 获取素材模板数据
func (m *sMaterial) ProcessMaterialTemplateScan(ctx context.Context, where, scan interface{}, orderBy ...string) error {
	if where == nil || g.IsNil(where) {
		return gerror.New(`缺少请求参数`)
	}
	orm := dao.MaterialTemplate.Ctx(ctx).Where(where)
	if len(orderBy) > 0 {
		orm = orm.Order(orderBy[0])
	}
	return orm.Scan(scan)
}

// ProcessMaterialTemplateTotal 统计模板总数数量
func (m *sMaterial) ProcessMaterialTemplateTotal(ctx context.Context, where interface{}) (total int, err error) {
	if where == nil || g.IsNil(where) {
		return 0, gerror.New(`缺少请求参数`)
	}
	return dao.MaterialTemplate.Ctx(ctx).Where(where).Count()
}
